<?php

namespace mybackend\controllers\cms;

use Yii;
use yii\data\Pagination;
use mybackend\controllers\BaseController;
use common\services\cms\ArticleService;
use common\models\cms\ArticleModel;
use common\error\ErrorCode;
use common\support\CacheManage;
use common\entities\cms\ArticleEntity;
use common\entities\cms\DirEntity;
use common\entities\myhtsq\ActionCode;
use common\support\QRSupport;
use yii\helpers\Html;
use common\support\OSS;

class ArticleController extends BaseController {
    
    public $_articleService;
    public $layout = '@app/views/cms/layouts/main.php';
    
    public function __construct($id, $module, ArticleService $ArticleService, $config = []) {
        $this->_articleService = $ArticleService;
        parent::__construct($id, $module, $config);
    }

    protected function roleAuthRules() {
        return [
            'actions' => ['Delete', 'Edit', 'GetList', 'QuickSet', 'Release', 'Save,UpdateQuickSet,UpdateEdit,UpdateList'],
            'rules' => [
                [
                    'allow' => true,
                    'actionCodeMaps' => [
                        'GetList' => ActionCode::CMS_ARTICLE_VIEW,
                        'Edit' => ActionCode::CMS_PUB_VIEW,
                        'Delete' => ActionCode::CMS_ARTICLE_MOD,
                        'QuickSet' => ActionCode::CMS_ARTICLE_MOD,
                        'Release' => ActionCode::CMS_ARTICLE_MOD,
                        'Save' => ActionCode::CMS_ARTICLE_MOD,
                        'UpdateQuickSet' => ActionCode::CMS_UPDATE_MOD,
                        'UpdateEdit' => ActionCode::CMS_UPDATE_MOD,
                        'UpdateList' => ActionCode::CMS_UPDATE_VIEW,
                    ]
                ]
            ]
        ];
    }    
    
    
    /**
     * 保存文章
     * @param copy int 是否复制
     * @param from string 文章来源
     */
    public function actionSave($copy = 0, $from = NULL) {
        $this->exitIfNotPost();
        $model = new ArticleModel(['scenario' => 'save']);
        if ($model->load(Yii::$app->request->post(), '')) {
            $model->orgGuids=Yii::$app->request->post("orgGuids",null);
            if($from == NULL){
                if(!$model->validate()) {
                    return $this->json(array(
                        "retCode" => ErrorCode::ERR_CMS_ARTICLE_EMPTY,
                        "retMsg" => join("\n", $model->getFirstErrors())
                    ));
                }
            }elseif($from == "update"){
                if (Yii::$app->request->post("title") == ""){
                    return $this->json(array(
                        "retCode" => ErrorCode::ERR_CMS_ARTICLE_EMPTY,
                        "retMsg" => "标题不能为空"
                    ));
                }
            }
            if ($model->abstractMode == 2){
                $model->abstract = $model->imageUrl;
            }
            $result = $this->_articleService->saveArticle($model);
            if ($copy != 0) {
                $model->aId = 0;
                $result = $this->_articleService->saveArticle($model);
            }
            $this->exportJson($result, $this->_articleService->getErrCode(), $this->_articleService->getErrMsg());
        } else {
            $this->errorParam();
        }     
    }

    /**
     * 更新pv
     * @param type $articleId
     */
    public function actionUpdatePv ($aId) {
        $this->exitIfNotPost();
        $this->_articleService->updatePv($aId);
    }

    /**
     * 编辑页
     * @param type $aId
     */
    public function actionEdit () {
        $dirModel = new DirEntity();
        $aId = $this->getParam("id");
        $result = $this->_articleService->getArticleInfo($aId);
        $result['model'] = $dirModel;
        $result['dirs'] = DirEntity::getOptions();
        return $this->json($result);
    }

    /**
     * 图片上传
     */
    public function actionMediaEdit() {
        $fs=array();
        foreach($_FILES as $k=>$v){
            $fs=$_FILES[$k];
            if($fs){
                if ($fs["error"]>0) {
                    echo json_encode(array('result'=>false,'errormsg'=>'上传错误'));
                }
                else if ((int)$fs["size"] > 1024*1024*20) {
                    echo "<script>alert('你的文件有点大哦~ 请压缩后上传！');</script>";
                }
                $torrent = explode(".", $fs["name"]);
                $fileend = end($torrent);
                $fileend = strtolower($fileend);
                //以文件的md5值，做为文件名
                $fileName = md5_file($fs["tmp_name"]) . "." . $fileend;
                $key = 'cmsmedia/' . date("Ym") . "/" . $fileName;
                OSS::upload($key, $fs["tmp_name"]);
                $url = OSS::getUrl($key);

                echo json_encode(array('result'=>true,'path'=>$url));

            }else{
                echo json_encode(array('result'=>false,'errormsg'=>'没有上传的文件'));
            }
        }
    }

    /**
     * 文件上传
     */
    public function actionFileUpload() {
        $files=$urlArray=$fs=array();
        $files_url= $files_name='';
        foreach($_FILES as $file){
            if(is_string($file['name'])){
                $files[]=$file;
            }elseif(is_array($file['name'])){
                $i=0;
                foreach($file['name'] as $key=>$value){
                    $files[$i]['name']=$file['name'][$key];
                    $files[$i]['type']=$file['type'][$key];
                    $files[$i]['tmp_name']=$file['tmp_name'][$key];
                    $files[$i]['error']=$file['error'][$key];
                    $files[$i]['size']=$file['size'][$key];
                    $i++;
                }
            }
        }

        foreach($files as $k=>$v){
            $fs=$files[$k];
            if($fs){
                if ($fs["error"]>0) {
                    echo json_encode(array('result'=>false,'errormsg'=>'上传错误'));
                }
                else if ((int)$fs["size"] > 1024*1024*20) {
                    echo "<script>alert('你的文件有点大哦~ 请压缩后上传！');</script>";
                }
                $torrent = explode(".", $fs["name"]);
                $fileend = end($torrent);
                $fileend = strtolower($fileend);
                //以文件的md5值，做为文件名
                $fileName = md5_file($fs["tmp_name"]) . "." . $fileend;
                $key = 'cmsmedia/' . date("Ym") . "/" . $fileName;
                OSS::upload($key, $fs["tmp_name"]);
                $url = OSS::getUrl($key);
                $urlArray[]= $url;
                $files_name.="@@".$fs["name"];
                $files_url.="@@".$url;
            }else{
                echo json_encode(array('result'=>false,'errormsg'=>'没有上传的文件'));
            }
        }
        echo json_encode(array('result'=>true,'path'=>$urlArray,'files_name'=>$files_name,'files_url'=>$files_url));
    }

    public function actionGetList () {
    $data = array();
    if ($this->isAjaxRequest()) {
        if (Yii::$app->request->get('update')) {
            $section  = Yii::$app->request->get('update');
            $value = Yii::$app->request->get('value');
            $ids = Yii::$app->request->get('ids');
            if ( ! empty($section) && ! empty($ids)) {
                $this->_articleService->updateBatch($section, $value, $ids); // 批量修改
            }
        }
        $page = Yii::$app->request->get('page', 1);
        $page_size = Yii::$app->request->get('rows', 20);
        $sidx = Yii::$app->request->get('sidx', 'id');
        $sord = Yii::$app->request->get('sord', 'DESC');
        $search = Yii::$app->request->get('keyword');
        $sidx = $this->_articleService->dealField($sidx);

        $updateDirIds = $this->_articleService->updateDirIds();
        $count = ArticleEntity::find();
        if ( ! empty($search)) {
            $count = $count->where(['like', 'title', $search])->orwhere(['like', 'tag', $search]);
        }
        $pages = new Pagination(['totalCount' => $count->andwhere(['del' => 0])->andWhere(['not in', 'dir_id', $updateDirIds])->count()]);
        $pages->setPageSize($page_size, true);

        $result = $this->_articleService->getArticleAllList($sidx, $sord, $page, $page_size, $search);
        foreach ($result as $key => $item) {
            $data['records'] = $pages->totalCount;
            $data['total'] = ceil($pages->totalCount / $page_size);
            $data['rows'][$key] = array(
                'author' => $item->author,
                'scan' => $item->scan,
                'id' => $item->a_id,
                'aId' => $item->a_id,
                'title' => html_entity_decode($item->title),
                'dirName' => $item->dir ? $item->dir->name : 'empty',
                'tag' => html_entity_decode($item->tag),
                'down_pv' => $item->down_pv,
                'collect' => $item->collect,
                'sort' => $item->sort,
                'inside' => $item->inside ? "已发布":"未发布",
                'outside' => $item->outside ? "已发布":"未发布",
                'modifiedBy' => $item->modified_by,
                'modifiedTime' => date('y-m-d H:i:s', $item->modified_time),
                'edit' => '<button onclick="updateStatus('.$item->a_id.', 1, $(this), 1)">头版</button>  '
                    .'<button onclick="updateStatus('.$item->a_id.', 2, $(this), 1)">取消头版</button>  '
                    .'<button onclick="updateStatus('.$item->a_id.', 1, $(this), 2)">发布</button>  '
                    .'<button onclick="updateStatus('.$item->a_id.', 2, $(this), 2)">取消发布</button>',
            );
        }
        echo json_encode($data);
        return Yii::$app->end();
    }
    return $this->render('getList');
}
    
    /**
     * 发布
     */
    public function actionRelease () {
        $aId = Yii::$app->request->post('id');
        $type = Yii::$app->request->post('type'); // 1发布，2取消发布
        if(empty($aId)){ 
            return Yii::$app->end();
        }
        $entity = ArticleEntity::find()->where(['a_id' => $aId])->one();
        $entity->status = ($type == 1 ? 1 : 0);
        $result = $entity->update();
        if ($result === false) {
            echo json_encode(['success' => 0]);
        } else {
            echo json_encode(['success' => 1]);
        }        
    }
    
    /**
     * 快速修改
     * @return type
     */
    public function actionQuickSet() {
        $attrArray=[];
        $id = $_POST['id'];
        unset($_POST['id']);
        unset($_POST['oper']);
        $model = ArticleEntity::find()->where(['a_id' => $id])->one();
        $model->modified_by = \Yii::$app->user->identity->username;
        $model->modified_time = time();
        if (!$model) {
            echo json_encode(['status' => false, 'errMsg' => \common\error\ErrorMsg::getDefaultMsg()]);
            return Yii::$app->end();
        }

        $dirEntity = DirEntity::find()->where(['id'=>$model->dir_id])->one();
        if(isset($_POST['inside'])){
            $attrArray['inside']=intval($_POST['inside']);
            if($_POST['inside']==1){
                if($dirEntity->status == 0) {
                    echo json_encode(['status' => false, 'content' => "该目录不对内显示"]);
                    return Yii::$app->end();
                }
                $attrArray['status']=intval($_POST['inside']);
            }else{
                $articleInfo=$this->_articleService->getArticleInfo($id);
                if($articleInfo['outside']==0){
                    $attrArray['status']=0;
                }
            }
        }
        if(isset($_POST['outside'])){
            $attrArray['outside'] = intval($_POST['outside']);
            if($_POST['outside']==1) {
                if($dirEntity->external_display == 0) {
                    echo json_encode(['status' => false, 'content' => "该目录不对外显示"]);
                    return Yii::$app->end();
                }
                $attrArray['status'] = intval($_POST['outside']);
            }else{
                $articleInfo=$this->_articleService->getArticleInfo($id);
                if($articleInfo['inside']=='0'){
                    $attrArray['status']=0;
                }
            }
        }
        $model->setAttributes($attrArray);

        $content = '';
        if (!$model->save()) {
            foreach ($model->getErrors() as $errors) {
                foreach ($errors as $error) {
                    if ($error != '')
                        $content.="{$error}";
                }
            }
            echo json_encode(['status' => false, 'errMsg' => $error]);
            return Yii::$app->end();
        }
    }
    
    /**
     * 删除
     */
    public function actionDelete () {
        $aId = Yii::$app->request->post('id');
        if(empty($aId)){ 
            echo json_encode(['success' => 0]);
        }
        $entity = ArticleEntity::find()->where(['a_id' => $aId])->one();
        $entity->del = 1;
        $result = $entity->update();
        if ($result === false) {
            echo json_encode(['success' => 0]);
        } else {
            echo json_encode(['success' => 1]);
        }         
    }
    
    /**
     * 二维码
     * @param type $url
     */
    public function actionImageurl($id){
        $url = "http://".$_SERVER['HTTP_HOST']."/details.html?articalId=".$id;
        //$url = urlencode($url);
        QRSupport::responseQR($url,240);
    }

    /**
     * 删除附件
     */
    public function actionFujianDel()
    {
        $a_id = Yii::$app->request->get('a_id');
        $url = Yii::$app->request->get('url');
        $this->_articleService->fujianDel($a_id,$url);
    }

    /*
     * 更新列表
     */
    public function actionUpdateList () {
        $data = array();
        if ($this->isAjaxRequest()) {
            if (Yii::$app->request->get('update')) {
                $section  = Yii::$app->request->get('update');
                $value = Yii::$app->request->get('value');
                $ids = Yii::$app->request->get('ids');
                if ( ! empty($section) && ! empty($ids)) {
                    $this->_articleService->updateBatch($section, $value, $ids); // 批量修改
                }
            }
            $page = Yii::$app->request->get('page', 1);
            $page_size = Yii::$app->request->get('rows', 20);
            $sidx = Yii::$app->request->get('sidx', 'id');
            $sord = Yii::$app->request->get('sord', 'DESC');
            $search = Yii::$app->request->get('keyword');
            $sidx = $this->_articleService->dealField($sidx);

            $updateDirIds = $this->_articleService->updateDirIds();
            $count = ArticleEntity::find();
            if ( ! empty($search)) {
                $count = $count->where(['like', 'title', $search])->orwhere(['like', 'tag', $search]);
            }
            $pages = new Pagination(['totalCount' => $count->andwhere(['del' => 0])->andWhere(['in', 'dir_id', $updateDirIds])->count()]);
            $pages->setPageSize($page_size, true);

            $result = $this->_articleService->getUpdateArticleList($sidx, $sord, $page, $page_size, $search);
            foreach ($result as $key => $item) {
                $data['records'] = $pages->totalCount;
                $data['total'] = ceil($pages->totalCount / $page_size);
                $data['rows'][$key] = array(
                    'author' => $item->author,
                    'ykscan' => $item->ykscan,
                    'scan' => $item->scan,
                    'id' => $item->a_id,
                    'aId' => $item->a_id,
                    'title' => html_entity_decode($item->title),
                    'dirName' => $item->dir ? $item->dir->name : 'empty',
                    'tag' => html_entity_decode($item->tag),
                    'sort' => $item->sort,
                    'status'=> $item->status ? "已发布":"未发布",
                    'modifiedBy' => $item->modified_by,
                    'modifiedTime' => date('y-m-d H:i:s', $item->modified_time),
                );
            }
            echo json_encode($data);
            return Yii::$app->end();
        }
        return $this->render('updateList');
    }
    /**
     * 更新说明编辑页
     * @param $aId int 文章id
     * @return array 文章内容
     */
    public function actionUpdateEdit () {
        $dirModel = new DirEntity();
        $aId = $this->getParam("id");
        $result = $this->_articleService->getArticleInfo($aId);
        if ($result['abstract_mode'] == 2){
            $result['imageUrl'] = $result['abstract'];
            $result['abstract'] = '';
        }
        if ($result['abstract_mode'] == 1){
            $result['image_url'] = '';
        }
        $result['model'] = $dirModel;
        $result['dirs'] = DirEntity::getUpdateDirs();
        return $this->json([
            'resCode' => 0,
            'data' => $result,
        ]);
    }

    /**
     * 快速修改
     */
    public function actionUpdateQuickSet() {
        $id = $_POST['id'];
        unset($_POST['id']);
        unset($_POST['oper']);
        $attrArray = $_POST;
        if (empty($attrArray)){
            echo json_encode(['status' => false, 'content' => "未选择所改属性"]);
            return Yii::$app->end();
        }
        if ($id == "" || $id == NULL){
            echo json_encode(['status' => false, 'content' => "未选择文章"]);
            return Yii::$app->end();
        }
        $setResult = $this->_articleService->updateQuickSet($id, $attrArray);
        if ($setResult === false){
            echo json_encode(['status' => false, 'content' => "修改失败"]);
            return Yii::$app->end();
        }
        echo json_encode(['status' => true, 'content' => "修改成功"]);
        return Yii::$app->end();
    }
}
